<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加/编辑商品</title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css" media="all">
    <style>
        .product-container {
            padding: 20px;
        }

        .product-container {
            background-color: #fff;
        }
        .product-container form {
            width: 800px;
            margin: 0 auto;
            padding: 30px;
            border: 1px solid #eee;
        } 

        /* .product-container form .layui-form-item {
            width: 700px;
        } */
        #moreUpload img,
        #moreUpload div {
            width: 80px;
            height: 80px;
            margin-right: 4px;
            position: relative;
        }
        #moreUpload div {
            border: 1px dashed #ccc;
        }
        #moreUpload div::before {
            position: absolute;
            bottom: 0;
            left: 0;
            content: '点击图片删除';
            width: 100%;
            height: 30%;
            font-size: 12px;
            text-align: center;
            color: #fff;
            background-color: rgba(0,0,0,.6);
            z-index: 1;
        }

        #moreUpload div:nth-of-type(1)::before {
            position: absolute;
            bottom: 0;
            left: 0;
            content: '主图';
            width: 100%;
            height: 30%;
            font-size: 12px;
            text-align: center;
            color: #fff;
            background-color: #FF5722;
            z-index: 1;
        }
        .layui-card-body ul {
            display: flex;
            justify-content: space-between;
            border-bottom: 1px solid #ccc;
            padding: 8px 0;
            padding-right: 10px;
        }
        .layui-card-body ul li {
            flex: 1;
            text-align: center;
        }
        .layui-card-body ul li input {
            width: 50px;
            padding: 4px 6px;
            box-sizing: border-box;
            border-radius: 6px;
            border: 1px solid #ccc;
            text-align: center;
        }
        .layui-card-body ul li:first-child input {
            width: 120px;
        }
        .info {
            position: relative;
        }
        .addInput {
            position: absolute;
            right: -16px;
            bottom: 10px;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div class="product-container">
        <form class="layui-form" lay-filter="product">
            <fieldset class="layui-elem-field layui-field-title">
                <legend>基本信息</legend>
            </fieldset>

            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>商品名称</label>
                <div class="layui-input-block">
                    <input type="text" name="goodsName" lay-verify="required" lay-reqtext="商品名称是必填项，岂能为空？" placeholder="请输入商品名称"
                        autocomplete="off" class="layui-input">
                </div>
            </div>
            
    
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>商品分类</label>
                <div class="layui-input-block">
                    <select name="categoryId" lay-verify="required" id="classify">
                        <option value=""></option>
                    </select>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品简介</label>
                <div class="layui-input-block">
                    <textarea placeholder="请输入内容" name="des" class="layui-textarea"></textarea>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>主图</label>
                <div class="layui-input-block">
                    <div class="layui-upload">
                        <blockquote class="layui-elem-quote layui-quote-nm" style="display: flex;align-items: center; width: 655px;">
                          <div class="layui-upload-list" id="moreUpload" style="margin-top: 10px; display: flex;align-items: center;"></div>
                          <button type="button" style="width: 80px; height: 80px; text-align: center;" class="layui-btn layui-btn-primary" id="uploadBtn"><i style="font-size: 28px;" class="layui-icon"></i></button> 
                       </blockquote>
                       <input type="hidden" name="skuImgUrl" id="skuImgUrl">
                      </div>
                </div>
            </div>

            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                <legend>价格库存</legend>
            </fieldset>

            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>规格名称</label>
                <div class="layui-input-block">
                    <input type="text" name="skuTitleType" lay-verify="required" lay-reqtext="规格名称是必填项，岂能为空？" placeholder="请输入规格名称"
                        autocomplete="off" class="layui-input">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>规格信息</label>
                <div class="layui-input-block">
                    <div class="layui-col-md6">
                        <div class="layui-card" style="border: 1px solid #ccc; width: 690px;">
                          <div class="layui-card-body">
                            <ul>
                                <li>子规格名称</li>
                                <li>售价</li>
                                <li>原价</li>
                                <li>库存</li>
                                <li class="spuIdFlag" style="display: none;">上下架状态</li>
                                <li>操作</li>
                                
                            </ul>
                            <div class="info">
                                <div class="info-input">
                                    <ul data-status="1">
                                        <li><input lay-verify="required" type="text" placeholder="名称"></li>
                                        <li><input lay-verify="required|number" type="text"> 元</li>
                                        <li><input lay-verify="required|number" type="text"> 元</li>
                                        <li><input lay-verify="required|number" type="text"> 件 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</li>
                                        <li id="frist-status" style="display: none;" data-type="1">已上架</li>
                                        <li></li>
                                    </ul>
                                </div>
                                <div class="addInput">
                                    <button type="button" class="input-add layui-btn layui-btn-xs">添加</button>
                                </div>
                            </div>
                          </div>
                        </div>
                      </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">商品编码</label>
                <div class="layui-input-block">
                    <input type="text" disabled name="spuNo" placeholder="自动生成无须填写"
                        autocomplete="off" class="layui-input">
                </div>
            </div>

            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                <legend>商品介绍</legend>
            </fieldset>

            <textarea id="productDetails" style="display: none;"></textarea>

            <!-- <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                <legend>销售属性</legend>
            </fieldset>

            <div class="layui-form-item">
                <label class="layui-form-label">上架状态</label>
                <div class="layui-input-block">
                    <input type="checkbox" checked="" name="status" lay-skin="switch" lay-filter="switchTest" lay-text="上架|稍后上架">
                </div>
            </div> -->
    
            
            <div class="layui-form-item" style="text-align:center; margin-top: 30px;">
                <div class="layui-input-block" style="margin-left: 0;">
                    <button type="submit" class="layui-btn" lay-submit="" lay-filter="addProduct">立即提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
    

</body>

<script src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>
<script src="../utils.js"></script>
<script src="./layedit.js"></script>

<script>
    layui.use(['upload', 'form', 'jquery', 'layedit'], function () {
        var upload = layui.upload,
            form = layui.form,
            $ = layui.jquery,
            layedit = layui.layedit;
            var editContext = "";
            var uploadArr = [];


            // 富文本配置
            editContext = layedit.build('productDetails', {
                uploadImage: {
                    url: window.baseUrl + '/file/uploadFile', 
                    type: 'post'
                }
            });

            var spuId = getQueryString("spuId");

            function getProductDetails () {
            
                if (spuId) {
                    ajax({
                        path: "/goods/getGoodsDetailForPc?spuId=" + spuId,
                        type: "GET",
                        success: function (res) {
                            console.log(res);
                            form.val('product', res);
                            uploadArr = res.spuImgUrl.split(',');
                            renderImg();

                            renderStatus (res.skuList)

                            $(".spuIdFlag").show();
                            $("#frist-status").show();
                            

                            try {
                                layedit.setContent(editContext, res.skuDetail);
                            } catch (error) {
                                console.log("发现异常，这个不重要我就不抛出了");
                            }

                            
                        }
                    }, $)
                }
            }

            function renderStatus (skuList) {
                $(".info-input").empty();
                $.each(skuList, function(index, item) {    
                    $(".info-input").append(`
                        <ul data-id="${item.id}" data-status="${item.status}">
                            <li><input lay-verify="required" placeholder="名称" type="text" value="${item.skuTitle}"></li>
                            <li><input lay-verify="required|number" type="text" value="${item.skuCurrPrice}"> 元</li>
                            <li><input lay-verify="required|number" type="text" value="${item.skuCostPrice}"> 元</li>
                            <li><input lay-verify="required|number" type="text" value="${item.skuNum}"> 件
                            <li data-type="${item.status == 1 ? "1" : "0"}">${item.status == 1 ? "已上架" : "已下架"}</li>
                            ${
                                !spuId ?  '<button type="button" class="input-del layui-btn layui-btn-xs layui-btn-danger">删除</button>'
                                : 
                                `   <li>
                                        <button type="button" data-type="1" class="skuStatusSj layui-btn layui-btn-xs">上架</button>
                                        <button type="button" style="margin-left:0;" data-type="0" class="skuStatusXj layui-btn layui-btn-xs layui-btn-danger">下架</button>
                                    </li>
                                `
                            }
                                
                            </li>
                        </ul>
                    `)
                })

                inputDel(skuList);

            }

            ajax({
                path: "/goods/getCategoryList?length=99999999",
                type: "GET",
                success: function (res) {
                    $.each(res.data, function(index, item) {
                        $('#classify').append('<option value="'+ item.id +'">'+ item.categoryName +'</option>')
                    })
                    getProductDetails();
                    form.render();
                }
            }, $)

            // 添加输入框
            $('.input-add').on("click", function() {
                $(".info-input").append(`
                    <ul data-status="1">
                        <li><input lay-verify="required" placeholder="名称" type="text"></li>
                        <li><input lay-verify="required|number" type="text"> 元</li>
                        <li><input lay-verify="required|number" type="text"> 元</li>
                        <li><input lay-verify="required|number" type="text"> 件 </li>
                        ${
                            spuId ?
                            '<li>未提交</li><li><button type="button" class="input-del layui-btn layui-btn-xs layui-btn-danger">删除</button></li>'
                            :
                            ""
                        }
                        ${
                            !spuId ?  '<li><button type="button" class="input-del layui-btn layui-btn-xs layui-btn-danger">删除</button></li>'
                            : 
                            `
                                <!-- <button type="button" data-type="1" class="skuStatusSj layui-btn layui-btn-xs">上架</button>
                                <button type="button" style="margin-left:0;" data-type="0" class="skuStatusXj layui-btn layui-btn-xs layui-btn-danger">下架</button> -->
                            `
                        }
                        
                    </ul>
                `)
                inputDel();
            })
            inputDel();
            function inputDel(skuList) {
                // if (!spuId) {
                //     $('.input-del').off().on("click", function() {
                //         $(this).parent().remove();
                //     })
                // }

                $('.input-del').off().on("click", function() {
                    $(this).parent().parent().remove();
                })
                
                $('.skuStatusSj').on('click', function() {
                    if (!$(this).parent().parent().attr('data-id')) {
                        layer.msg("上架失败，需要添加保存后在进行修改")
                        return false;
                    }
                    if ($(this).parent().parent().index() >= 0) {
                        skuList[$(this).parent().parent().index()].status = 1;
                        renderStatus (skuList);
                        layer.msg("上架成功");
                    }
                    
                })

                $('.skuStatusXj').on('click', function() {
                    if (!$(this).parent().parent().attr('data-id')) {
                        layer.msg("下架失败，需要添加保存后在进行修改")
                        return false;
                    }
                    if ($(this).parent().parent().index()>=0) {
                        skuList[$(this).parent().parent().index()].status = 0;
                        renderStatus (skuList) ;
                        layer.msg("下架成功");
                    }

                    
                })
            }

            // 删除图片
            function delImg() {
                $('#moreUpload div').off().on('click', function() {
                    uploadArr.splice($(this).index(), 1);
                    $("#skuImgUrl").val(uploadArr.join(","));
                    renderImg();
                })
            }

            // 渲染图片
            function renderImg() {
                $('#moreUpload').empty();
                $.each(uploadArr, function(index, item) {
                    $('#moreUpload').append('<div><img src="'+ item +'" alt="" class="layui-upload-img"></div>')
                })
                delImg()
            }   

            //多图片上传
            var htmlVal = $("#skuImgUrl").val();
            upload.render({
                elem: '#uploadBtn'
                ,url: window.baseUrl + '/file/uploadFile' //改成您自己的上传接口
                ,multiple: true
                , headers: {
                    Authorization: localStorage.token
                }
                ,before: function(obj){
                    loading = layer.load(1, {
                        shade: [0.6,'#000'] //0.1透明度的白色背景
                    });

                    //预读本地文件示例，不支持ie8
                    obj.preview(function(index, file, result){
                        $('#moreUpload').append('<div><img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img"></div>')
                    });
                }
                ,done: function(res){
                    //上传完毕
                    uploadArr.push(res.data);
                    layer.closeAll();
                    var urlstr = uploadArr.join(',');
                    layer.msg("上传成功！")
                    $("#skuImgUrl").val(htmlVal ? (htmlVal + ',' + urlstr) : urlstr);
                    // 重新排版图片
                    renderImg();
                    delImg();
                }
            });


            // 提交
            form.on("submit(addProduct)", function(obj) {
                delete obj.field.file;

                obj.field.special = 0;
                obj.field.skuDetailImgUrl = "null";
                obj.field.skuCoversUrl = uploadArr[0];
                var skuArr = [];
                $.each($('.info-input ul'), function(index, el) {
                    let a = {
                        skuTitleType: obj.field.skuTitleType,
                        skuImgUrl: uploadArr.join(","),
                        skuTitle: $(el).children('li').eq(0).children("input").val(),
                        skuCurrPrice: $(el).children('li').eq(1).children("input").val(),
                        skuCostPrice: $(el).children('li').eq(2).children("input").val(),
                        skuNum: $(el).children('li').eq(3).children("input").val(),
                        status: $(el).attr('data-status'),
                        skuCoversUrl: uploadArr[0],
                        skuNo: obj.field.skuNo,
                        skuDetailImgUrl: "null"
                    }
                    
                    if (spuId) {
                        a.id = $(el).attr('data-id');
                    } else {
                        delete obj.field.spuNo
                    }

                    skuArr.push(a)
                })

                obj.field.skuList = skuArr;
                // obj.field.status = obj.field.status == "on" ? 1 : 0;
                obj.field.status = 1;
                obj.field.skuDetail = layedit.getContent(editContext);

                if (spuId) {
                    obj.field.id = spuId;
                }

                ajax({
                    path: "/goods/saveOrUpdateGoods",
                    data: obj.field,
                    success: function (res) {
                        layer.msg("操作成功! ");
                        history.go(-1);
                    }
                }, $)

                console.log(obj.field);
                return false;
            })

    });
</script>

</html>